<!--当前编辑页面动态数据源配置管理-->

<template>
  <div>
    <Drawer title="当前编辑页面动态数据源配置管理"
            :width="'50%'"
            placement="left"
            :closable="true"
            :mask-closable="true"
            :draggable="false"
            transfer
            v-model="visible"
            @on-close="cancel"
            :styles="$PnUtil.buildDrawerStyleByHasFooter()">

      <div v-if="show" class="m-b-10px">
        <Row>
          <i-col span="8">
            <div class="statistics-item" style="background-color: #2196F3;">
              <strong>{{ datasourceStatisticsNum('api') }}</strong>
              <h3>API接口</h3>
            </div>
          </i-col>
          <i-col span="8">
            <div class="statistics-item" style="background-color: #4CAF51;">
              <strong>{{ datasourceStatisticsNum('database') }}</strong>
              <h3>关系型数据库</h3>
            </div>
          </i-col>
          <i-col span="8">
            <div class="statistics-item" style="background-color: #F44337;">
              <strong>{{ datasourceStatisticsNum('csv') }}</strong>
              <h3>CSV文件</h3>
            </div>
          </i-col>
        </Row>
      </div>

      <!--<Form class="func-comp-form" :label-width="80">
        <FormItem label="数据源类型">
          <Select v-model="filterDsType">
            <Option value="api">API</Option>
            <Option value="database">数据库</Option>
          </Select>
        </FormItem>
      </Form>-->

      <div class="toolbar-wrapper">
        <Form class="func-comp-form" ref="replaceForm" :model="replaceFormData" inline>
          <Alert show-icon type="info">
            可以通过字符替换，改变所有组件中的API接口地址。
          </Alert>
          <FormItem prop="sourceString">
            <i-input type="text" v-model="replaceFormData.sourceString" placeholder="">
              <span slot="prepend">被替换字符</span>
            </i-input>
          </FormItem>
          <FormItem prop="newString">
            <i-input type="text" v-model="replaceFormData.newString" placeholder="">
              <span slot="prepend">替换字符</span>
            </i-input>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="submitReplaceForm">全部替换</Button>
            <Button type="default" class="m-l-5px" @click="resetReplaceForm">清空</Button>
          </FormItem>
        </Form>
      </div>

      <div v-if="filterDsType == 'api'">
        <div class="datasource-item-wrapper" v-for="(layoutItem, index) in newLayoutItems" :key="index">
          <div class="image-wrapper">
            <img class="w-h-full" :src="thumbnailSrc(layoutItem.component.name)"/>
          </div>
          <div class="body-wrapper">
            <Row>
              <i-col span="24">
                <Input type="text" size="small" style="width: 100%;" v-model="layoutItem.component.compConfigData.ds_apiPath"/>
              </i-col>
            </Row>
          </div>
        </div>
      </div>

      <!--<Collapse :accordion="false">
        <Panel :name="layoutItem.id" v-for="(layoutItem, index) in newLayoutItems" :key="index">
          {{layoutItem.aliasName ? layoutItem.aliasName : componentAliasName(layoutItem.component.name)}} - API：{{layoutItem.component.compConfigData.ds_apiPath}}
          <div slot="content">
            <Form class="func-comp-form" :label-width="80">
              <FormItem label="接口地址">
                <Input type="text" style="width: 100%;" v-model="layoutItem.component.compConfigData.ds_apiPath"/>
              </FormItem>
              &lt;!&ndash;<FormItem label="使用服务器代理请求">
                <i-switch v-model="layoutItem.component.compConfigData.ds_useHttpServerProxy">
                  <span slot="open"></span>
                  <span slot="close"></span>
                </i-switch>
              </FormItem>
              <FormItem v-show="layoutItem.component.compConfigData.ds_apiMethod != null" label="请求方式">
                <Select v-model="layoutItem.component.compConfigData.ds_apiMethod">
                  <Option value="GET">GET</Option>
                  <Option value="POST">POST</Option>
                </Select>
              </FormItem>
              <FormItem v-show="layoutItem.component.compConfigData.ds_apiHeaders != null" label="Headers">

                <Input class="m-t-5px" type="textarea" :rows="6" v-model="layoutItem.component.compConfigData.ds_apiHeaders"/>
              </FormItem>
              <FormItem v-show="layoutItem.component.compConfigData.ds_apiMethod == 'POST' && layoutItem.component.compConfigData.ds_apiPostData != null"
                        label="POST请求参数">
                <Input class="m-t-5px" type="textarea" :rows="6" v-model="layoutItem.component.compConfigData.ds_apiPostData"/>
              </FormItem>&ndash;&gt;
            </Form>
          </div>
        </Panel>
      </Collapse>-->

      <DrawerFooter>
        <Button type="text" class="m-r-5px" @click="recover">恢复</Button>
        <Button type="primary" @click="confirmTheChange">提交修改</Button>
      </DrawerFooter>

    </Drawer>
  </div>
</template>

<script>
  import _ from 'lodash'

  import { createHelpers } from 'vuex-map-fields';

  const { mapFields } = createHelpers({
    getterType: 'designer/getField',
    mutationType: 'designer/updateField',
  });

  export default {
    name: "DataSourceGlobalSetting",
    props: {
      show: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        visible: this.show,

        newPageMetadata: null,
        newLayoutItems: [],

        filterDsType: 'api',

        replaceFormData: {
          sourceString: '',
          newString: ''
        }
      }
    },
    mounted() {

    },
    methods: {

      clearData () {
        this.newPageMetadata = null;
        this.newLayoutItems = [];
      },

      init () {
        this.clearData();
        this.newPageMetadata = this.$PnUtil.deepClone(this.pageMetadata);
        this.newLayoutItems = _.filter(this.newPageMetadata.layout.layoutItems, (o) => {
          if (o.component.id) {
            if (o.component.compConfigData.ds_type == this.filterDsType)
              return true
            else
              return false
          }
          return false
        });
        // 格式化ds_apiHeaders和ds_apiPostData
        /*this.newLayoutItems.forEach(layoutItem => {
          if (layoutItem.component.compConfigData.ds_apiHeaders) {
            layoutItem.component.compConfigData.ds_apiHeaders = JSON.stringify(layoutItem.component.compConfigData.ds_apiHeaders, null, 2);
          }
          if (layoutItem.component.compConfigData.ds_apiPostData) {
            layoutItem.component.compConfigData.ds_apiPostData = JSON.stringify(layoutItem.component.compConfigData.ds_apiPostData, null, 2);
          }
        })*/
      },

      recover () {
        this.$Modal.confirm({
          title: '提醒',
          content: '确认恢复到修改前的状态吗？',
          onOk: () => {
            this.init()
          }
        });
      },

      /**
       * 统计各数据源数量
       * @param type
       * @returns {number}
       */
      datasourceStatisticsNum (type) {
        let num = 0;
        this.newLayoutItems.forEach(layoutItem => {
          if (layoutItem.component.id) {
            if (layoutItem.component.compConfigData.ds_type != undefined && layoutItem.component.compConfigData.ds_type == type) {
              num++
            }
          }
        })
        return num
      },

      submitReplaceForm () {
        this.$refs['replaceForm'].validate((valid) => {
          if (valid) {
            this.newLayoutItems.forEach(layoutItem => {
              if (layoutItem.component.id && layoutItem.component.compConfigData.ds_type == 'api') {
                layoutItem.component.compConfigData.ds_apiPath = layoutItem.component.compConfigData.ds_apiPath.replaceAll(this.replaceFormData.sourceString, this.replaceFormData.newString)
              }
            })
          }
        })
      },

      resetReplaceForm () {
        this.$refs['replaceForm'].resetFields()
      },

      confirmTheChange () {
        this.$Modal.confirm({
          title: '提醒',
          content: '将当前编辑后的数据作用于当前编辑页面，提交后请记得保存页面，确认提交吗？',
          onOk: () => {
            let mergeLayoutItems = this.$PnUtil.deepMerge(this.newPageMetadata.layout.layoutItems, this.newLayoutItems)
            this.$store.commit('designer/setLayoutItems', mergeLayoutItems);
            // this.$EventBus.$emit('pn_save_current_page');
            this.cancel()
          }
        });
      },

      componentAliasName (componentName) {
        if (componentName) {
          let str = JSON.parse(localStorage.getItem('allCompinfoObj'))[componentName].alias_name;
          if (str)
            return str;
          else
            return componentName
        }else {
          return "未绑定功能组件！"
        }
      },

      thumbnailSrc (componentName) {
        if (componentName) {
          try {
            return require('../../../../components/functional/' + JSON.parse(localStorage.getItem('allCompinfoObj'))[componentName].thumbnail_uri)
          }catch (e) {
            console.error('组件图片路径错误');
            return require('../../../../assets/image/thumbnail/thumbnail-default.png');
          }
        }else {
          return require('../../../../assets/image/thumbnail/thumbnail-default.png')
        }
      },

      cancel () {
        this.visible = false;
        this.$emit('cancel', this.visible)
      }
    },
    computed: {
      ...mapFields({
        pageMetadata: 'pageMetadata'
      })
    },
    watch: {
      show (val) {
        this.visible = val;
        if (val) {
          this.init()
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .statistics-item {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 10px;
    color: #fff;
    text-align: center;
  }
  .statistics-item strong {
    font-size: 20px;
  }

  .toolbar-wrapper {
    background-color: #424242;
    padding: 10px 10px 10px 10px;
    margin: 10px 0px 10px 0px;
    border: 1px solid #757575;
    border-radius: 3px;
  }

  .datasource-item-wrapper {
    width: 100%;
    height: 46px;
    background-color: #424242;
    margin-bottom: 5px;
    border: 1px solid #616161;
    &:last-child {
      margin-bottom: 0px;
    }
    .image-wrapper {
      float: left;
      width: 80px;
      height: 100%;
    }
    .body-wrapper {
      padding: 0px 10px 0px 10px;
      width: calc(100% - 80px);
      float: left;
      line-height: 42px;
    }
  }
</style>
